
package com.example.sistemacompras.db;

import com.example.sistemacompras.entity.Person;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

public final class DatabaseHandler extends SQLiteOpenHelper {
	private static DatabaseHandler instance = null;

    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_NAME = "iesb_android";

    private static final String TABLE_PERSONS = "persons";

    private static final String KEY_ID = "_id";

    private static final String KEY_NAME = "name";

    private static final String KEY_EMAIL = "email";

    private static final String KEY_IMAGE = "image";

    private static final String KEY_PASS = "password";
    
    public static DatabaseHandler getInstance(Activity activity){
    	if(instance==null){
    		instance = new DatabaseHandler(activity);
    	}
    	return instance;
    }
    
    public static DatabaseHandler getInstance(){
    	return instance;
    }

    private DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_PERSONS_TABLE = "CREATE TABLE " + TABLE_PERSONS + "(" + KEY_ID
                + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_EMAIL + " TEXT, " + KEY_IMAGE
                + " BLOB, " + KEY_PASS + " TEXT)";
        db.execSQL(CREATE_PERSONS_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_PERSONS);
        onCreate(db);
    }

    public boolean createPerson(Person person) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, person.getName());
        values.put(KEY_EMAIL, person.getEmail());
        if (person.getPhoto() != null) {
            values.put(KEY_IMAGE, getBitmapAsByteArray(person.getPhoto()));
        }
        values.put(KEY_PASS, person.getPassword());

        long ret = db.insert(TABLE_PERSONS, null, values);
        db.close();
        return ret == -1 ? false : true;
    }

    public static Person getPerson(String email, String senha) {
        List<Person> list = getAllPersons();
        Person pesquisa = null;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getEmail().equals(email) && list.get(i).getPassword().equals(senha)) {
                pesquisa = list.get(i);
            }
        }
        return pesquisa;
    }

    public static List<Person> getAllPersons() {
        List<Person> personList = new ArrayList<Person>();

        String selectQuery = "SELECT * FROM " + TABLE_PERSONS;

        SQLiteDatabase db = DatabaseHandler.getInstance().getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                byte[] imgByte = cursor.getBlob(3);

                Person person = new Person();
                person.setId(Integer.parseInt(cursor.getString(0)));
                person.setName(cursor.getString(1));
                person.setEmail(cursor.getString(2));
                if (cursor.getBlob(3) != null) {
                    person.setPhoto(BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length));
                }
                person.setPassword(cursor.getString(4));

                personList.add(person);
            } while (cursor.moveToNext());
        }

        return personList;
    }

    public static int getPersonsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_PERSONS;
        SQLiteDatabase db = DatabaseHandler.getInstance().getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        return cursor.getCount();
    }

    public static int updatePerson(Person person) {
        SQLiteDatabase db = DatabaseHandler.getInstance().getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, person.getName());
        values.put(KEY_EMAIL, person.getEmail());
        values.put(KEY_IMAGE, getBitmapAsByteArray(person.getPhoto()));
        values.put(KEY_PASS, person.getPassword());

        return db.update(TABLE_PERSONS, values, KEY_ID + " = ?", new String[] {
            String.valueOf(person.getId())
        });
    }

    public static void deletePerson(Person person) {
        SQLiteDatabase db = DatabaseHandler.getInstance().getWritableDatabase();
        db.delete(TABLE_PERSONS, KEY_ID + " = ?", new String[] {
            String.valueOf(person.getId())
        });
        db.close();
    }

    public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, outputStream);
        return outputStream.toByteArray();
    }
}
